# -*- coding: utf-8 -*-

from rest_framework.response import Response
from ..debug import print_obj

import logging
logger = logging.getLogger('bt_server')


class ShowRequestResponseInfoMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # show sth before resonse
        logger.info('========= {} {} ========='.format(request.method, request.get_full_path()))

        if request.method == 'GET':
            logger.info(request.GET)
        elif request.method == 'POST':
            logger.info(request.POST)

        # print_obj(request)
        response = self.get_response(request)
        # show sth after response
        if isinstance(response, Response):
            if hasattr(response, 'data'):
                if response.data and (not 'code' in response.data):
                    response.data['code'] = 0
                    response.data['codemsg'] = u'请求成功'
                    new_response = Response(
                        data=response.data,
                        status=response.status_code,
                        template_name=response.template_name,
                        # headers=response.headers,
                        exception=response.exception,
                        content_type=response.content_type)
                    new_response['Access-Control-Allow-Origin'] = '*'
                    new_response['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
                    new_response.accepted_renderer = response.accepted_renderer
                    new_response.accepted_media_type = response.accepted_media_type
                    new_response.renderer_context = response.renderer_context
                    # logger.info(new_response.accepted_renderer)
                    response = new_response

        logger.info('========================== END ==========================')
        return response
